/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package IU;

import Logica.Apuesta;
import Logica.Carrera;
import Logica.Fachada;
import Logica.Jornada;
import Logica.Jugador;
import Logica.Participante;
import Utilidades.Observable;
import Utilidades.Observador;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.JOptionPane;

/**
 *
 * @author jarzarello
 */
public class JugadorApuesta extends javax.swing.JDialog implements Observador {

    /**
     * Creates new form JugadorApuesta
     */
    public JugadorApuesta(java.awt.Frame parent, boolean modal) {

        super(parent, modal);
        initComponents();
        Fachada.getInstancia().agregar(this);
        try {
            CargarDatos();
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }
    }

    private Carrera CarreraSeleccionada;
    private Participante ParticipanteSeleccionado;
    ArrayList<Participante> participantes;

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lblNumCarrera = new javax.swing.JLabel();
        lblNomCarrera = new javax.swing.JLabel();
        lblNumCarreraData = new javax.swing.JLabel();
        lblNomCarreraData = new javax.swing.JLabel();
        lblEstadoCarrera = new javax.swing.JLabel();
        lblEstadoCarreraData = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        lstCaballosParticipantes = new javax.swing.JList();
        jLabel1 = new javax.swing.JLabel();
        lblUsuario = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        txtUsuario = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        txtMonto = new javax.swing.JTextField();
        btnApostar = new javax.swing.JButton();
        lblCaballoSeleccionado = new javax.swing.JLabel();
        lblCaballoSelData = new javax.swing.JLabel();
        btnSeleccionCaballo = new javax.swing.JButton();
        txtPwd = new javax.swing.JPasswordField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        lblNumCarrera.setText("Número carrera: ");

        lblNomCarrera.setText("Nombre carrera: ");

        lblEstadoCarrera.setText("Estado carrera: ");

        jScrollPane1.setViewportView(lstCaballosParticipantes);

        jLabel1.setText("Caballos en carrera: ");

        lblUsuario.setText("Usuario: ");

        jLabel2.setText("Contraseña: ");

        jLabel3.setText("Monto a apostar: ");

        btnApostar.setText("Apostar");
        btnApostar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnApostarActionPerformed(evt);
            }
        });

        lblCaballoSeleccionado.setText("Caballo seleccionado: ");

        btnSeleccionCaballo.setText("Seleccionar");
        btnSeleccionCaballo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSeleccionCaballoActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(lblNumCarrera)
                                .addGap(18, 18, 18)
                                .addComponent(lblNumCarreraData))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(lblNomCarrera)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(lblNomCarreraData))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(lblEstadoCarrera)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(lblEstadoCarreraData))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addGap(18, 18, 18)
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 184, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(btnSeleccionCaballo))
                            .addComponent(btnApostar))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(lblUsuario, javax.swing.GroupLayout.Alignment.LEADING))
                                .addGap(40, 40, 40)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(txtUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(0, 0, Short.MAX_VALUE))
                                    .addComponent(txtPwd)))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addGap(18, 18, 18)
                                .addComponent(txtMonto)))
                        .addGap(82, 82, 82)
                        .addComponent(lblCaballoSeleccionado)
                        .addGap(18, 18, 18)
                        .addComponent(lblCaballoSelData)))
                .addGap(113, 113, 113))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblNumCarrera)
                    .addComponent(lblNumCarreraData))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblNomCarrera)
                    .addComponent(lblNomCarreraData))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblEstadoCarrera)
                    .addComponent(lblEstadoCarreraData))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnSeleccionCaballo)
                    .addComponent(jLabel1)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 35, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(lblCaballoSeleccionado)
                        .addComponent(lblCaballoSelData))
                    .addComponent(txtUsuario, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblUsuario, javax.swing.GroupLayout.Alignment.TRAILING))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtPwd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtMonto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(btnApostar)
                .addGap(52, 52, 52))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnSeleccionCaballoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSeleccionCaballoActionPerformed
        // TODO add your handling code here:
        try {
            SeleccionarCaballo();
        }
        catch (IndexOutOfBoundsException e) {
            JOptionPane.showMessageDialog(null, "Seleccione un caballo");
        }
        catch (Exception ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }

    }//GEN-LAST:event_btnSeleccionCaballoActionPerformed

    private void btnApostarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnApostarActionPerformed
        // TODO add your handling code here:
        Apostar();
    }//GEN-LAST:event_btnApostarActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnApostar;
    private javax.swing.JButton btnSeleccionCaballo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblCaballoSelData;
    private javax.swing.JLabel lblCaballoSeleccionado;
    private javax.swing.JLabel lblEstadoCarrera;
    private javax.swing.JLabel lblEstadoCarreraData;
    private javax.swing.JLabel lblNomCarrera;
    private javax.swing.JLabel lblNomCarreraData;
    private javax.swing.JLabel lblNumCarrera;
    private javax.swing.JLabel lblNumCarreraData;
    private javax.swing.JLabel lblUsuario;
    private javax.swing.JList lstCaballosParticipantes;
    private javax.swing.JTextField txtMonto;
    private javax.swing.JPasswordField txtPwd;
    private javax.swing.JTextField txtUsuario;
    // End of variables declaration//GEN-END:variables

    private void CargarDatos() throws Exception {
        Jornada j = PanelJugador.getInstancia().getHipodromoSeleccionado().buscarJornada(new Date());
        Carrera c = j.buscarCarreraActual();
        if (c != null) {
            CarreraSeleccionada = c;
            lblNomCarreraData.setText(c.getNombre());
            lblEstadoCarreraData.setText(c.getEstadoString());
            lblNumCarreraData.setText(Integer.toString(c.getNumero()));
            listarParticipantes();
        } else {
            throw new Exception("No hay carreras.");
        }
    }

    private void listarParticipantes() {
        participantes = CarreraSeleccionada.getParticipantes();
        ArrayList<String> listado = new ArrayList();
        for (Participante p : participantes) {
            listado.add(formatear(p));
        }
        lstCaballosParticipantes.setListData(listado.toArray());
    }

    // primero valido los datos del usuario
    // luego que la carrera no se encuentre cerrada.
    private void Apostar() {
        try {
            CheckearEstado();
            Jugador jugador = ValidarJugador();
            int monto = Integer.parseInt(txtMonto.getText());
            jugador.ValidarMonto(monto);
            Apuesta apuesta = new Apuesta(monto, jugador, ParticipanteSeleccionado);
            CarreraSeleccionada.agregarApuesta(apuesta);
            JOptionPane.showMessageDialog(null, "Apuesta Realizada");
            LimpiarParametros();
        } catch (NumberFormatException ex) {
            JOptionPane.showMessageDialog(this, "Número inválido");
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }
    }

    private void SeleccionarCaballo() throws Exception {
        Fachada f = Fachada.getInstancia();
        Participante participante = participantes.get(lstCaballosParticipantes.getSelectedIndex());
        if (participante != null) {
            ParticipanteSeleccionado = participante;
            lblCaballoSelData.setText(participante.getCaballo().getNombre());
        } else {
            throw new Exception("Seleccione un caballo");
        }
    }

    private Jugador ValidarJugador() throws Exception {
        Fachada f = Fachada.getInstancia();
        Jugador j = f.buscarJugador(txtUsuario.getText(), txtPwd.getText());
        if (j == null) {
            throw new Exception("Los Datos no son correctos");
        }
        return j;
    }

    private String formatear(Participante p) {
        return p.getNumero() + ", " + p.getCaballo().getNombre() + ", " + p.getDividendo();
    }

    private void CheckearEstado() throws Exception {
        if (CarreraSeleccionada.getEstado() != Carrera.abierta) {
            throw new Exception("La carrera no está abierta para realizar apuestas");
        }
    }

    private void LimpiarParametros() {
        txtMonto.setText("");
        txtPwd.setText("");
        txtUsuario.setText("");
        ParticipanteSeleccionado = null;
        lblCaballoSelData.setText("");
    }

    @Override
    public void actualizar(Observable origen, Object param) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    
}
